<template>
  <div class="location-device-registration bg-background text-foreground p-6">
    <h2 class="text-2xl font-bold mb-6">定位设备登记</h2>

    <div class="bg-card text-card-foreground p-6 rounded-lg shadow-sm mb-6">

      <QueryForm :model="search" :formItems="formItems" @search="allsearch" @reset="resetSearch" />
    </div>

    <div class="flex flex-wrap justify-between mb-6">
      <div class="space-x-2 mb-2 sm:mb-0" v-if="activeTab === '登记'">
        <!-- <button @click="openAddDialog" class="btn btn-primary">新增</button>
        <button @click="deleteSelected" class="btn btn-destructive">删除</button> -->

        <!-- <button @click="exportData" class="btn btn-secondary">导出</button> -->
        <el-button type="primary" @click="openAddDialog" style="width: 75px; height: 30px;">新增</el-button>
        <el-button @click="openImportDialog">导入</el-button>
        <el-button @click="deleteSelected" style="width: 75px; height: 30px;">删除</el-button>
        <el-button @click="exportData(equipmentData, '定位设备', selectedIds)"
          style="width: 75px; height: 30px;">导出</el-button>
      </div>
      <div class="space-x-2 mb-2 sm:mb-0" v-else>
        <el-button v-if="activeTab === '发放'" @click="exportData(issueData, '发放设备', selectedIds)"
          style="width: 75px; height: 30px;">导出</el-button>
        <el-button v-else @click="exportData(RETURN_DATEs, '归还设备', selectedIds)"
          style="width: 75px; height: 30px;">导出</el-button>
      </div>
      <div class="space-x-2" style="float: right;">
        <div class="tabs bg-card mb-6 inline-flex rounded-lg p-1">
          <!-- <button v-for="tab in ['登记',
            '发放',
            '归还']" :key="tab" @click="btntab(tab)" :class="[
              'rounded-md px-4 py-2 font-medium transition-colors duration-200',
              activeTab === tab
                ? 'bg-primary text-primary-foreground'
                : 'text-muted-foreground hover:bg-muted',
            ]" style="margin:0 5px">
            {{ tab }}
          </button> -->
          <el-button :type="getButtonType(tab)" plain v-for="tab in ['登记',
            '发放',
            '归还']" :key="tab" @click="btntab(tab)" style="width: 75px; height: 30px;">{{ tab }}</el-button>
        </div>
        <!-- <button @click="registerEquipment" class="btn btn-primary">登记</button>
        <button @click="issueEquipment" class="btn btn-secondary">发放</button>
        <button @click="returnEquipment" class="btn btn-secondary">归还</button> -->
      </div>
    </div>

    <div v-if="activeTab === '登记'" class="bg-card rounded-lg shadow-sm overflow-x-auto">
      <el-table v-loading="loading" :data="displayedEquipmentData" style="width: 100%" ref="tableRef" align="center"
        class="data-table" :header-cell-style="headerCellStyle" @selection-change="handleSelectionChange"
        :row-key="rowKey" empty-text="暂无数据">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column label="序号" width="55" header-align="center" align="center">
          <template #default="scope">
            {{ startIndex + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="DEVICE_CODE" label="设备编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DEVICE_NAME" label="设备名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="PURCHASE_DATE" label="购置日期" header-align="center" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.PURCHASE_DATE) }}
          </template>
        </el-table-column>
        <el-table-column prop="PURCHASE_AMOUNT" label="购置金额" header-align="center" align="center">
          <template #default="scope">
            {{ formatCurrency(scope.row.PURCHASE_AMOUNT) }}
          </template>
        </el-table-column>
        <el-table-column prop="DEPARTMENT" label="归属部门" header-align="center" align="center"></el-table-column>
        <el-table-column prop="MANUFACTURER" label="厂家信息" header-align="center" align="center"></el-table-column>
        <el-table-column prop="LAST_REGISTRATION" label="最近维护记录" header-align="center" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.LAST_REGISTRATION) }}
          </template>
        </el-table-column>
        <el-table-column prop="STATUS" label="使用状态" header-align="center" align="center">
          <template #default="scope">
            <span :style="{ color: scope.row.STATUS === '闲置中' ? '#70B603' : '#F59A23' }">{{ scope.row.STATUS }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="editEquipment(scope.row)">编辑</el-button>
            <el-button type="warning" v-if="scope.row.STATUS === '闲置中'" @click="issueEquipment(scope.row)"
              link>发放</el-button>
            <el-button type="danger" v-else @click="returnEquipment(scope.row)" link>归还</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination bg-card text-card-foreground p-4 mt-4 flex items-center justify-between">
        <div>
          <p class="text-sm text-muted-foreground">
            一共检索到 <span class="font-medium total-num">{{ totalItems }}</span> 条信息
          </p>
        </div>
        <div class="flex items-center space-x-2">
          <button @click="prevPage" :disabled="currentPage === 1" class="btn btn-secondary btn-sm"
            :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }">
            上一页
          </button>
          <span class="text-sm text-muted-foreground">
            {{ currentPage }} / {{ totalPages }}
          </span>
          <button @click="nextPage" :disabled="currentPage === totalPages" class="btn btn-secondary btn-sm"
            :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }">
            下一页
          </button>
        </div>
      </div>
    </div>

    <div v-if="activeTab === '发放'" class="bg-card rounded-lg shadow-sm overflow-x-auto">

      <el-table v-loading="loading" :data="displayedEquipmentDataFF" style="width: 100%" ref="tableRefFF" align="center"
        class="data-table" :header-cell-style="headerCellStyle" @selection-change="handleSelectionChange"
        :row-key="rowKey" empty-text="暂无数据">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column label="序号" width="55" header-align="center" align="center">
          <template #default="scope">
            {{ startIndexFF + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="GET_BY" label="领取人姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="ID_CORD" label="证件号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="PHONE_NUMBER" label="联系方式" header-align="center" align="center"></el-table-column>
        <el-table-column prop="GET_DATE" label="领用日期" header-align="center" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.GET_DATE) }}
          </template>
        </el-table-column>
        <el-table-column prop="DEVICE_CODE" label="设备编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DEVICE_NAME" label="设备名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="ISSUE_BY" label="发放人" header-align="center" align="center"></el-table-column>
        <el-table-column prop="RETURN_DATA" label="预计归还日期" header-align="center" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.RETURN_DATE) }}
          </template>
        </el-table-column>
        <el-table-column prop="STAMP" label="备注" header-align="center" align="center"></el-table-column>
        <!-- <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button @click="returnEquipment(scope.row)" link style="color: #A30014;">归还</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <div class="pagination bg-card text-card-foreground p-4 mt-4 flex items-center justify-between">
        <div>
          <p class="text-sm text-muted-foreground">
            一共检索到 <span class="font-medium total-num">{{ totalItemsFF }}</span> 条信息
          </p>
        </div>
        <div class="flex items-center space-x-2">
          <button @click="prevPageFF" :disabled="currentPageFF === 1" class="btn btn-secondary btn-sm"
            :class="{ 'opacity-50 cursor-not-allowed': currentPageFF === 1 }">
            上一页
          </button>
          <span class="text-sm text-muted-foreground">
            {{ currentPageFF }} / {{ totalPagesFF }}
          </span>
          <button @click="nextPageFF" :disabled="currentPageFF === totalPagesFF" class="btn btn-secondary btn-sm"
            :class="{ 'opacity-50 cursor-not-allowed': currentPageFF === totalPagesFF }">
            下一页
          </button>
        </div>
      </div>
    </div>
    <div v-if="activeTab === '归还'" class="bg-card rounded-lg shadow-sm overflow-x-auto">

      <el-table v-loading="loading" :data="displayedEquipmentDataGH" style="width: 100%" ref="tableRefGH" align="center"
        class="data-table" :header-cell-style="headerCellStyle" @selection-change="handleSelectionChange"
        :row-key="rowKey" empty-text="暂无数据">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column label="序号" width="55" header-align="center" align="center">
          <template #default="scope">
            {{ startIndexGH + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="GET_BY" label="领取人姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="RETURN_DATE" label="归还日期" header-align="center" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.RETURN_DATE) }}
          </template>
        </el-table-column>
        <el-table-column prop="DEVICE_CODE" label="设备编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DEVICE_NAME" label="设备名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="RECIEVE_BY" label="接收人" header-align="center" align="center"></el-table-column>
        <el-table-column prop="STATUS_BOOK" label="外观检查" header-align="center" align="center"></el-table-column>
        <el-table-column prop="STAMP_RETURN" label="备注" header-align="center" align="center"></el-table-column>
      </el-table>
      <div class="pagination bg-card text-card-foreground p-4 mt-4 flex items-center justify-between">
        <div>
          <p class="text-sm text-muted-foreground">
            一共检索到 <span class="font-medium total-num">{{ totalItemsGH }}</span> 条信息
          </p>
        </div>
        <div class="flex items-center space-x-2">
          <button @click="prevPageGH" :disabled="currentPageGH === 1" class="btn btn-secondary btn-sm"
            :class="{ 'opacity-50 cursor-not-allowed': currentPageGH === 1 }">
            上一页
          </button>
          <span class="text-sm text-muted-foreground">
            {{ currentPageGH }} / {{ totalPagesGH }}
          </span>
          <button @click="nextPageGH" :disabled="currentPageGH === totalPagesGH" class="btn btn-secondary btn-sm"
            :class="{ 'opacity-50 cursor-not-allowed': currentPageGH === totalPagesGH }">
            下一页
          </button>
        </div>
      </div>
    </div>


    <!-- Add Equipment Dialog -->
    <!-- <div v-if="isAddDialogOpen"
      class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
      <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[800px]">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold">登记新设备</h3>
          <button @click="closeAddDialog" class="text-muted-foreground hover:text-foreground">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
              xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>

        <form @submit.prevent="addNewEquipment">
          <div class="grid grid-cols-3 gap-4">
            <div>
              <label for="code" class="block text-sm font-medium text-gray-700">设备编码：</label>
              <input type="text" id="code" v-model="newEquipment.deviceCode" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="name" class="block text-sm font-medium text-gray-700">设备名称：</label>
              <input type="text" id="name" v-model="newEquipment.DEVICE_NAME" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="purchaseDate" class="block text-sm font-medium text-gray-700">购置日期：</label>
              <input type="date" id="purchaseDate" v-model="newEquipment.purchaseDate" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="purchaseAmount" class="block text-sm font-medium text-gray-700">购置金额：</label>
              <input type="number" id="purchaseAmount" v-model="newEquipment.purchaseAmount" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="department" class="block text-sm font-medium text-gray-700">归属部门：</label>
              <select id="status" v-model="newEquipment.Department" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                <option value="管委会">管委会</option>

              </select>

            </div>
            <div>
              <label for="manufacturer" class="block text-sm font-medium text-gray-700">厂家信息：</label>

              <input type="text" id="department" v-model="newEquipment.Manufacturer" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
          </div>
          <div class="mt-4 flex justify-end space-x-2">
            <button type="submit"
              class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2">保存</button>
            <button type="button" @click="closeAddDialog"
              class="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 focus:outline-none focus:ring-2 focus:ring-secondary focus:ring-offset-2">取消</button>
          </div>
        </form>
      </div>
    </div> -->
    <el-dialog class="dialog-from" v-model="isAddDialogOpen" :title="isEditDialogOpen ? '定位设备新增' : '定位设备编辑'" width="900"
      destroy-on-close align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-form :model="newEquipment" label-width="auto" :rules="rulesAdd" ref="formRefAdd">
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="设备编码：" label-position="top" prop="DEVICE_CODE">
                  <el-input v-model="newEquipment.DEVICE_CODE" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备名称：" label-position="top" prop="DEVICE_NAME">
                  <el-input v-model="newEquipment.DEVICE_NAME" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="购置日期：" label-position="top" prop="PURCHASE_DATE">
                  <input type="datetime-local" v-model="newEquipment.PURCHASE_DATE"
                    class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="购置金额：" label-position="top" prop="PURCHASE_AMOUNT">
                  <el-input v-model="newEquipment.PURCHASE_AMOUNT" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="归属部门：" label-position="top" prop="DEPARTMENT">
                  <el-input type="text" v-model="newEquipment.DEPARTMENT" placeholder="请输入" />
                  <!-- <el-select v-model="newEquipment.Department" placeholder="请选择" clearable>
                    <el-option label="管委会" value="管委会" />
                  </el-select> -->

                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="厂家信息：" label-position="top" prop="MANUFACTURER">
                  <el-input v-model="newEquipment.MANUFACTURER" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addNewEquipment">确认</el-button>
          <el-button @click="closeAddDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Edit Equipment Dialog -->
    <!-- <div v-if="isEditDialogOpen" class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
      <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[800px]">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold">编辑设备</h3>
          <button @click="closeEditDialog" class="text-muted-foreground hover:text-foreground">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>

        <form @submit.prevent="updateEquipment">
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label for="device_code" class="block text-sm font-medium text-gray-700">设备编码：</label>
              <input type="text" id="device_code" v-model="editingEquipment.device_code" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="device_name" class="block text-sm font-medium text-gray-700">设备名称：</label>
              <input type="text" id="device_name" v-model="editingEquipment.device_name" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="purchaseDate" class="block text-sm font-medium text-gray-700">购置日期：</label>
              <input type="date" id="purchaseDate" v-model="editingEquipment.purchaseDate" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="purchaseAmount" class="block text-sm font-medium text-gray-700">购置金额：</label>
              <input type="number" id="purchaseAmount" v-model="editingEquipment.purchaseAmount" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="department" class="block text-sm font-medium text-gray-700">归属部门：</label>
              <input type="text" id="department" v-model="editingEquipment.department" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="manufacturer" class="block text-sm font-medium text-gray-700">厂家信息：</label>
              <input type="text" id="manufacturer" v-model="editingEquipment.manufacturer" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="status" class="block text-sm font-medium text-gray-700">使用状态：</label>
              <select id="status" v-model="editingEquipment.status" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                <option value="闲置中">闲置中</option>
                <option value="借用中">借用中</option>
              </select>
            </div>

          </div>
          <div class="mt-4 flex justify-end space-x-2">
            <button type="submit"
              class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2">保存</button>
            <button type="button" @click="closeEditDialog"
              class="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 focus:outline-none focus:ring-2 focus:ring-secondary focus:ring-offset-2">取消</button>
          </div>
        </form>
      </div>
    </div> -->

    <!-- View Equipment Details Dialog -->
    <div v-if="isViewDialogOpen" class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
      <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[800px]">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold">查看设备详情</h3>
          <button @click="closeViewDialog" class="text-muted-foreground hover:text-foreground">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>

        <div class="grid grid-cols-2 gap-4">
          <div v-for="(value, key) in viewingEquipment" :key="key" class="mb-2">
            <strong>{{ getChineseFieldName(key) }}:</strong> {{ formatFieldValue(key, value) }}
          </div>
        </div>

        <div class="flex justify-center mt-4">
          <button @click="closeViewDialog" class="bg-secondary text-secondary-foreground px-4 py-2 rounded">关闭</button>
        </div>
      </div>
    </div>

    <!-- Import Dialog -->
    <el-dialog width="400px" class="dialog-from" v-model="isImportDialogOpen" title="导入" destroy-on-close align-center
      :before-close="closeImportDialog">
      <input accept=".csv, .xlsx" type="file" @change="handleFileUpload" />
      <div class="flex justify-end">
        <el-button @click="closeImportDialog">
          取消
        </el-button>
        <el-button type="primary" @click="importData">
          导入
        </el-button>
      </div>
    </el-dialog>



    <!-- Issue Dialog -->
    <!-- <div v-if="isIssueDialogOpen"
      class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
      <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[800px]">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold">定位设备发放</h3>
          <button @click="closeIssueDialog" class="text-muted-foreground hover:text-foreground">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
              xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>

        <form @submit.prevent="submitIssue">
          <div class="grid grid-cols-3 gap-4">
            <div>
              <label for="issueTo" class="block text-sm font-medium text-gray-700">设备编码：</label>
              <input type="text" id="issueTo" v-model="issueFormData.deviceCode" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="issueTo" class="block text-sm font-medium text-gray-700">设备名称：</label>
              <input type="text" id="issueTo" v-model="issueFormData.DEVICE_NAME" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="issueTo" class="block text-sm font-medium text-gray-700">领取人姓名：</label>
              <input type="text" id="issueTo" v-model="issueFormData.GET_BY" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="issueTo" class="block text-sm font-medium text-gray-700">证件号码：</label>
              <input type="text" id="issueTo" v-model="issueFormData.ID_CORD" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="issueTo" class="block text-sm font-medium text-gray-700">联系方式：</label>
              <input type="text" id="issueTo" v-model="issueFormData.PHONE_NUMBER" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="issueDate" class="block text-sm font-medium text-gray-700">领用日期：</label>
              <input type="date" id="issueDate" v-model="issueFormData.GET_DATE" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="issueTo" class="block text-sm font-medium text-gray-700">发放人：</label>
              <input type="text" id="issueTo" v-model="issueFormData.ISSUE_BY" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="issueDate" class="block text-sm font-medium text-gray-700">归还日期：</label>
              <input type="date" id="issueDate" v-model="issueFormData.RETURN_DATE" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
          </div>
          <div>
            <label for="remarks" class="block text-sm  text-gray-700">备注：</label>
            <input type="text" id="remarks" v-model="issueFormData.STAMP" required
              class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
          </div>
          <div class="mt-4 flex justify-end space-x-2">
            <button type="submit"
              class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2">保存</button>
            <button type="button" @click="closeIssueDialog"
              class="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 focus:outline-none focus:ring-2 focus:ring-secondary focus:ring-offset-2">取消</button>
          </div>
        </form>
      </div>
    </div> -->
    <el-dialog class="dialog-from" v-model="isIssueDialogOpen" title="定位设备发放" width="900" destroy-on-close align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-form :model="issueFormData" label-width="auto" :rules="rules" ref="formRef">
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="设备编码：" label-position="top" prop="DEVICE_CODE">
                  <el-input v-model="issueFormData.DEVICE_CODE" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备名称：" label-position="top" prop="DEVICE_NAME">
                  <el-input v-model="issueFormData.DEVICE_NAME" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="领取人姓名：" label-position="top" prop="GET_BY">
                  <el-input v-model="issueFormData.GET_BY" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="证件号码：" label-position="top" prop="ID_CORD">
                  <el-input v-model="issueFormData.ID_CORD" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系方式：" label-position="top" prop="PHONE_NUMBER">
                  <el-input type="number" v-model="issueFormData.PHONE_NUMBER" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="领用日期：" label-position="top" prop="GET_DATE">
                  <input type="datetime-local" v-model="issueFormData.GET_DATE"
                    class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="发放人：" label-position="top" prop="ISSUE_BY">
                  <el-input type="text" v-model="issueFormData.ISSUE_BY" />
                  <!-- <el-select v-model="issueFormData.ISSUE_BY" placeholder="请选择" clearable>
                    <el-option label="管委会" value="管委会" />
                  </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="预计归还日期：" label-position="top" prop="RETURN_DATE">
                  <input type="datetime-local" v-model="issueFormData.RETURN_DATE"
                    class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                </el-form-item>
              </el-col>
              <el-col :span="8"></el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="24">
                <el-form-item label="备注：" label-position="top" prop="STAMP">
                  <el-input v-model="issueFormData.STAMP" type="textarea" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitIssue">确认</el-button>
          <el-button @click="closeIssueDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Return Dialog -->
    <!-- <div v-if="isReturnDialogOpen"
      class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
      <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[800px]">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold">设备归还</h3>
          <button @click="closeReturnDialog" class="text-muted-foreground hover:text-foreground">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
              xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>

        <form @submit.prevent="submitReturn">
          <div class="grid grid-cols-3 gap-4">
            <div>
              <label for="issueTo" class="block text-sm font-medium text-gray-700">领取人姓名：</label>
              <input type="text" id="issueTo" v-model="returnFormData.GET_BY" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="issueDate" class="block text-sm font-medium text-gray-700">归还日期：</label>
              <input type="date" id="issueDate" v-model="returnFormData.realRurnData" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="issueTo" class="block text-sm font-medium text-gray-700">设备编码：</label>
              <input type="text" id="issueTo" v-model="returnFormData.deviceCode" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="issueTo" class="block text-sm font-medium text-gray-700">设备名称：</label>
              <input type="text" id="issueTo" v-model="returnFormData.DEVICE_NAME" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>


            <div>
              <label for="issueTo" class="block text-sm font-medium text-gray-700">接受人：</label>
              <el-input type="text" v-model="returnFormData.reciveBy" />
            </div>
            <div>
              <label for="issueTo" class="block text-sm font-medium text-gray-700">外观检查：</label>
              <select id="status" v-model="returnFormData.reciveStatus" required
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                <option value="完好">完好</option>
                <option value="损坏">损坏</option>
              </select>
            </div>

          </div>
          <div>
            <label for="remarks" class="block text-sm  text-gray-700">备注：</label>
            <input type="text" id="remarks" v-model="returnFormData.stampReturn" required
              class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
          </div>
          <div class="mt-4 flex justify-end space-x-2">
            <button type="submit"
              class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2">保存</button>
            <button type="button" @click="closeReturnDialog"
              class="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 focus:outline-none focus:ring-2 focus:ring-secondary focus:ring-offset-2">取消</button>
          </div>
        </form>
      </div>
    </div> -->
    <el-dialog class="dialog-from" v-model="isReturnDialogOpen" title="定位设备归还" width="900" destroy-on-close align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-form :model="returnFormData" label-width="auto" :rules="rulesReturn" ref="formRefReturn">
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="领取人姓名：" label-position="top" prop="GET_BY">
                  <el-input v-model="returnFormData.GET_BY" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="归还日期：" label-position="top" prop="RETURN_DATE">
                  <input type="date" v-model="returnFormData.RETURN_DATE" required
                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备编码：" label-position="top" prop="DEVICE_CODE">
                  <el-input v-model="returnFormData.DEVICE_CODE" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="设备名称：" label-position="top" prop="DEVICE_NAME">
                  <el-input v-model="returnFormData.DEVICE_NAME" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="接受人：" label-position="top" prop="RECIEVE_BY">
                  <el-input v-model="returnFormData.RECIEVE_BY" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="外观检查：" label-position="top" prop="STATUS_BOOK">
                  <el-select v-model="returnFormData.STATUS_BOOK" placeholder="请选择" clearable>
                    <el-option label="完好" value="完好" />
                    <el-option label="损坏" value="损坏" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="24">
                <el-form-item label="备注：" label-position="top" prop="STAMP_RETURN">
                  <el-input v-model="returnFormData.STAMP_RETURN" type="textarea" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitReturn">确认</el-button>
          <el-button @click="closeReturnDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx'
import { dayjs } from "element-plus"
const { proxy } = getCurrentInstance()
import { exportData } from '#/utils/exportfile.js'
const apiBaseUrl = ref(proxy.$currentUrl + '/api')

const search = ref({
  DEVICE_CODE: '',
  DEVICE_NAME: '',
  STATUS: ''
})
const formItems = ref([
  {
    label: '设备编码：',
    model: 'DEVICE_CODE',
    type: 'input',
    placeholder: '请输入',
  },

  {
    label: '设备名称：',
    model: 'DEVICE_NAME',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: 'GPS追踪器', value: 'GPS追踪器' },
      { label: '监控摄像头', value: '监控摄像头' },

    ],
  },
  // {
  //   label: '使用状态：',
  //   model: 'DEVICE_NAME',
  //   type: 'select',
  //   placeholder: '请选择',
  //   options: [
  //     { label: '闲置中', value: '闲置中' },
  //     { label: '借用中', value: '借用中' },
  //   ],
  // },
])


const selectAll = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const currentPageFF = ref(1)
const pageSizeFF = ref(10)
const currentPageGH = ref(1)
const pageSizeGH = ref(10)

const isAddDialogOpen = ref(false)
const isEditDialogOpen = ref(true)
const isViewDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const isIssueDialogOpen = ref(false)
const isReturnDialogOpen = ref(false)

const newEquipment = ref({})
const editingEquipment = ref({})
const viewingEquipment = ref({})
const issueFormData = ref({
  ID: '',
  DEVICE_CODE: '',// 设备编码
  DEVICE_NAME: '',// 设备名称
  GET_BY: '',// 领取人
  ID_CORD: '',// 证件号码
  PHONE_NUMBER: '',// 联系电话
  GET_DATE: '',// 领取日期
  ISSUE_BY: '',// 发放人
  RETURN_DATE: '',// 归还日期
  STAMP: '',// 发放的备注
})
const returnFormData = ref({
  ID: '',
  GET_BY: '',// 领取人
  RETURN_DATE: '',// 归还日期
  DEVICE_CODE: '',// 设备编码
  DEVICE_NAME: '',// 设备名称
  RECIEVE_BY: '',
  STATUS_BOOK: '',
  STAMP_RETURN: '',// 归还备注
})

const totalItems = computed(() => equipmentData.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))
const startIndex = computed(() => (currentPage.value - 1) * pageSize.value)

const totalItemsFF = computed(() => issueData.value.length)
const totalPagesFF = computed(() => Math.ceil(totalItemsFF.value / pageSizeFF.value))
const startIndexFF = computed(() => (currentPageFF.value - 1) * pageSizeFF.value)

const totalItemsGH = computed(() => issueData.value.length)
const totalPagesGH = computed(() => Math.ceil(totalItemsGH.value / pageSizeGH.value))
const startIndexGH = computed(() => (currentPageGH.value - 1) * pageSizeGH.value)

const displayedEquipmentData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return equipmentData.value.slice(start, end)
})
const displayedEquipmentDataFF = computed(() => {
  const start = (currentPageFF.value - 1) * pageSizeFF.value
  const end = start + pageSizeFF.value
  return issueData.value.slice(start, end)
})
const displayedEquipmentDataGH = computed(() => {
  const start = (currentPageGH.value - 1) * pageSizeGH.value
  const end = start + pageSizeGH.value
  return RETURN_DATEs.value.slice(start, end)
})
const importFile = ref(null)
const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
  console.log('File selected:', importFile.value?.name) // 添加日志
}

const resetSearch = () => {
  search.value = {
    DEVICE_CODE: '',
    DEVICE_NAME: '',
    STATUS: ''
  }
  allsearch()
}

const openAddDialog = () => {
  isAddDialogOpen.value = true

  newEquipment.value = {}
}

const closeAddDialog = () => {
  isAddDialogOpen.value = false
  isEditDialogOpen.value = true
  newEquipment.value = {}
}

const addNewEquipment = async () => {
  console.log(newEquipment.value)
  try {
    if (isEditDialogOpen.value) {
      const response = await axios.post(apiBaseUrl.value + '/location-devices', newEquipment.value)
      alert(response.data.message || '创建设备成功')

    } else {
      const response = await axios.put(`${apiBaseUrl.value}/location-devices/${newEquipment.value.ID}`, newEquipment.value)
      alert(response.data.message || '编辑设备成功')
    }
    closeAddDialog()
    await allsearch()
  } catch (error) {
    console.error('创建设备失败:', error)
    alert('创建设备失败: ' + (error.response?.data?.message || error.message))
  }
}

const deleteSelected = async () => {
  // const selectedIds = equipmentData.value.filter(equipment => equipment.selected).map(equipment => equipment.ID)
  if (selectedIds.value.length === 0) {
    alert('请选择要删除的设备')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 个设备吗？`)) {
    try {
      await Promise.all(selectedIds.value.map(item => axios.delete(`${apiBaseUrl.value}/location-devices/${item.ID}`)))
      alert('删除成功')
      await allsearch()
    } catch (error) {
      console.error('删除设备失败:', error)
      alert('删除设备失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

const openImportDialog = () => {
  isImportDialogOpen.value = true
}


const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
  console.log('Import dialog closed') // 添加日志
}
const importData = async (file) => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  try {
    const response = await axios.post(`${apiBaseUrl.value}/location-devices/Plan/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    alert(response.data.message || '导入成功')
    closeImportDialog()
    await allsearch()
  } catch (error) {
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }
}

// const exportData = () => {
//   if (activeTab.value == '登记') {
//     const wb = XLSX.utils.book_new()
//     const ws = XLSX.utils.json_to_sheet(equipmentData.value)
//     XLSX.utils.book_append_sheet(wb, ws, '定位设备')
//     XLSX.writeFile(wb, '定位设备.xlsx')
//   } else if (activeTab.value == '发放') {
//     const wb = XLSX.utils.book_new()
//     const ws = XLSX.utils.json_to_sheet(issueData.value)
//     XLSX.utils.book_append_sheet(wb, ws, '发放设备')
//     XLSX.writeFile(wb, '发放设备.xlsx')
//   } else {
//     const wb = XLSX.utils.book_new()
//     const ws = XLSX.utils.json_to_sheet(RETURN_DATE.value)
//     XLSX.utils.book_append_sheet(wb, ws, '归还设备')
//     XLSX.writeFile(wb, '归还设备.xlsx')
//   }


// }

const toggleSelectAll = () => {
  equipmentData.value.forEach(equipment => equipment.selected = selectAll.value)
}

const editEquipment = (equipment) => {
  newEquipment.value = { ...equipment }
  newEquipment.value.PURCHASE_DATE = dayjs(newEquipment.value.PURCHASE_DATE).format('YYYY-MM-DD')
  isAddDialogOpen.value = true
  isEditDialogOpen.value = false
}

const updateEquipment = async () => {
  try {
    const response = await axios.put(`${apiBaseUrl.value}/location-devices/${editingEquipment.value.ID}`, editingEquipment.value)
    alert(response.data.message || '更新设备成功')
    isEditDialogOpen.value = false
    await allsearch()
  } catch (error) {
    console.error('更新设备失败:', error)
    alert('更新设备失败: ' + (error.response?.data?.message || error.message))
  }
}

const viewDetails = (equipment) => {
  viewingEquipment.value = { ...equipment }
  isViewDialogOpen.value = true
}

const registerEquipment = () => {
  // Implement register equipment logic
}

const issueEquipment = (item) => {
  isIssueDialogOpen.value = true
  issueFormData.value.ID = item.ID
  issueFormData.value.DEVICE_CODE = item.DEVICE_CODE
  issueFormData.value.DEVICE_NAME = item.DEVICE_NAME


}
const formRef = ref(null)
const submitIssue = async () => {
  try {
    console.log(issueFormData.value)
    formRef.value.validate(async (valid) => {
      if (valid) {
        console.log(11112)
        await axios.put(`${apiBaseUrl.value}/location-issue/issue/${issueFormData.value.ID}`, issueFormData.value)
        alert('发放成功')
        await allsearch()
        closeIssueDialog()
      }
    })
  }
  catch (error) {
    console.error('发放失败:', error)
    alert(
      '发放失败: ' + (error.response?.data?.message || error.message),
    )
  }
}

const closeIssueDialog = () => {
  isIssueDialogOpen.value = false
  issueFormData.value = {
    ID: '',
    DEVICE_CODE: '',// 设备编码
    DEVICE_NAME: '',// 设备名称
    GET_BY: '',// 领取人
    ID_CORD: '',// 证件号码
    PHONE_NUMBER: '',// 联系电话
    GET_DATE: '',// 领取日期
    ISSUE_BY: '',// 发放人
    RETURN_DATE: '',// 归还日期
    STAMP: '',// 发放的备注
  }
}

const returnEquipment = (item) => {
  isReturnDialogOpen.value = true
  returnFormData.value.ID = item.ID
  returnFormData.value.DEVICE_CODE = item.DEVICE_CODE
  returnFormData.value.DEVICE_NAME = item.DEVICE_NAME
  returnFormData.value.GET_BY = item.GET_BY
}
const submitReturn = async () => {
  console.log(returnFormData.value)
  if (returnFormData.value.STATUS_BOOK == '损坏' && returnFormData.value.STAMP_RETURN == '') {
    return alert('请填写备注')
  }
  try {

    await axios.put(`${apiBaseUrl.value}/location-issue/return/${returnFormData.value.ID}`, returnFormData.value)
    allsearch()
    alert('归还成功')
  } catch (error) {
    alert('归还失败')
  }
  closeReturnDialog()
}

const closeReturnDialog = () => {
  isReturnDialogOpen.value = false
  returnFormData.value = {
    GET_BY: '',// 领取人
    realRurnData: '',// 归还日期
    DEVICE_CODE: '',// 设备编码
    DEVICE_NAME: '',// 设备名称
    reciveBy: '',
    reciveStatus: '',
    stampReturn: '',// 归还备注
  }
}

// 添加格式化函数
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const formatCurrency = (amount) => {
  return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(amount)
}

const closeEditDialog = () => {
  isEditDialogOpen.value = false
  editingEquipment.value = {}
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  viewingEquipment.value = {}
}

const getChineseFieldName = (key) => {
  const fieldNameMap = {
    device_code: '设备编码',
    device_name: '设备名称',
    device_type: '设备类型',
    purchase_date: '购置日期',
    purchase_amount: '购置金额',
    department: '归属部门',
    manufacturer: '厂家信息',
    last_registration: '最近登记记录',
    status: '使用状态'
  }
  return fieldNameMap[key] || key
}
const getButtonType = (tab) => {
  switch (tab) {
    case '登记':
      return 'primary'
    case '发放':
      return 'warning'
    case '归还':
      return 'danger'
    default:
      return 'plain'
  }
}
const formatFieldValue = (key, value) => {
  if (key === 'purchase_date' || key === 'last_registration') {
    return formatDateTime(value)
  } else if (key === 'purchase_amount') {
    return formatCurrency(value)
  } else {
    return value
  }
}
////////////////////////////
const activeTab = ref('登记')
const equipmentData = ref([])
const issueData = ref([])
const RETURN_DATEs = ref([])
const btntab = (data) => {
  activeTab.value = data
  allsearch()
}
const tableRefFF = ref(null)
const tableRefGH = ref(null)
// 搜索
const allsearch = async () => {
  selectedIds.value = []
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
  if (tableRefFF.value) {
    tableRefFF.value.clearSelection()
  }
  if (tableRefGH.value) {
    tableRefGH.value.clearSelection()
  }
  currentPage.value = 1
  currentPageFF.value = 1
  currentPageGH.value = 1
  pageSize.value = 10
  if (activeTab.value == '登记') {
    dengjisearch()
  } else if (activeTab.value == '发放') {
    issuesearch()
  } else {
    returnsearch()
  }

}
//
const dengjisearch = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/location-devices/search`, { params: search.value })
    equipmentData.value = response.data.map(equipment => ({ ...equipment, selected: false }))
    loading.value = false
  } catch (error) {
    console.error('搜索设备失败:', error)
    alert('搜索设备失败: ' + (error.response?.data?.message || error.message))
  }

}
const issuesearch = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/location-issue/search/issue`, { params: search.value })
    issueData.value = response.data.map(equipment => ({ ...equipment, selected: false }))
  } catch (error) {
    console.error('搜索设备失败:', error)
    alert('搜索设备失败: ' + (error.response?.data?.message || error.message))
  }
}
const returnsearch = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/location-issue/search/return`, { params: search.value })
    RETURN_DATEs.value = response.data.map(equipment => ({ ...equipment, selected: false }))
    loading.value = false
  } catch (error) {
    console.error('搜索设备失败:', error)
    alert('搜索设备失败: ' + (error.response?.data?.message || error.message))
  }
}
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    // allsearch()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    // allsearch()
  }
}
const prevPageFF = () => {
  if (currentPageFF.value > 1) {
    currentPageFF.value--
    // allsearch()
  }
}

const nextPageFF = () => {
  if (currentPageFF.value < totalPagesFF.value) {
    currentPageFF.value++
    // allsearch()
  }
}
const prevPageGH = () => {
  if (currentPageGH.value > 1) {
    currentPageGH.value--
    // allsearch()
  }
}

const nextPageGH = () => {
  if (currentPageGH.value < totalPagesGH.value) {
    currentPageGH.value++
    // allsearch()
  }
}
const rowKey = (row) => row.ID // 设置行的唯一标识
const tableRef = ref(null)
// 表头样式
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const isDialogType = ref('')
const loading = ref(false)
const selectedIds = ref([])
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
// 添加格式化日期时间的函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}
const rules = reactive({
  DEVICE_CODE: [
    { required: true, message: '请输入设备编码', trigger: 'blur' },
  ],
  DEVICE_NAME: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
  ],
  GET_BY: [
    { required: true, message: '请输入领取人姓名', trigger: 'blur' },
  ],
  ID_CORD: [
    { required: true, message: '请输入证件号码', trigger: 'blur' },
  ],
  PHONE_NUMBER: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
  ],
  GET_DATE: [
    { required: true, message: '请选择领用日期', trigger: 'change' },
  ],
  ISSUE_BY: [
    { required: true, message: '请输入发放人', trigger: 'blur' },
  ],
  RETURN_DATE: [
    { required: true, message: '请选择预计归还日期', trigger: 'change' },
  ],
})
const rulesAdd = reactive({
  DEVICE_CODE: [
    { required: true, message: '请输入设备编码', trigger: 'blur' },
  ],
  DEVICE_NAME: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
  ],
  purchaseDate: [
    { required: true, message: '请选择购置日期', trigger: 'change' },
  ],
  purchaseAmount: [
    { required: true, message: '请输入购置金额', trigger: 'blur' },
  ],
  Department: [
    { required: true, message: '请选择归属部门', trigger: 'change' },
  ],
  Manufacturer: [
    { required: true, message: '请输入厂家信息', trigger: 'blur' },
  ],
})
const rulesReturn = reactive({
  GET_BY: [
    { required: true, message: '请输入领取人姓名', trigger: 'blur' },
  ],
  realRurnData: [
    { required: true, message: '请选择归还日期', trigger: 'change' },
  ],
  DEVICE_CODE: [
    { required: true, message: '请输入设备编码', trigger: 'blur' },
  ],
  reciveBy: [
    { required: true, message: '请输入接受人', trigger: 'blur' },
  ],
})
onMounted(() => {
  allsearch()
})
</script>

<style scoped>
.input,
.select {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-outline {
  @apply border border-input bg-background hover:bg-accent hover:text-accent-foreground;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

:deep(.dialog-from .el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}

.box-title {
  margin-bottom: 10px;
}

:deep(.box-color) {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}

.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}
</style>
